package com.xujl.fastlib.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    public static boolean isEmpty (String str) {
        if (str == null) {
            return true;
        }
        str = str.trim();
        return str.equals("") || str.equals("null") || str.equals("NULL");
    }

    public static boolean isEmpty (CharSequence str) {
        if (str == null) {
            return true;
        }
        return isEmpty(str.toString());
    }

    public static String stringToNotNull (String str) {
        return isEmpty(str) ? "" : str;
    }

    public static boolean equals (String s1, String s2) {
        if (s1 == null || s2 == null) {
            return false;
        }
        return s1.equals(s2);
    }

    public static int length (String str) {
        if (isEmpty(str)) {
            return 0;
        }
        return str.length();
    }

    public static String humpToLine (String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static List<String> humpToList (String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        List<String> result = new ArrayList<>();
        while (matcher.find()) {
            result.add(matcher.group(0).toLowerCase());
        }
        return result;
    }

    /**
     * 是否包含
     *
     * @param source
     * @param s
     * @return
     */
    public static boolean contains (final CharSequence source, final CharSequence s) {
        if (isEmpty(s)) {
            return false;
        }
        return source.toString().contains(s);
    }

    public static boolean startWith (String source, String str) {
        if (isEmpty(source) || isEmpty(str)) {
            return false;
        }
        return source.startsWith(str);
    }

    public static boolean endWith (String source, String str) {
        if (isEmpty(source) || isEmpty(str)) {
            return false;
        }
        return source.endsWith(str);
    }
}
